package com.park.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Aaron
 * 字符编码 Filter
 */
public class CharsetEncodingFilter implements Filter {

	private String encoding = null;

	private ServletContext servletContext;

	@Override
	public void init(FilterConfig filterConfig) {
		this.encoding = filterConfig.getInitParameter("encoding");
		this.servletContext = filterConfig.getServletContext();
	}

	@Override
	public void doFilter(ServletRequest request,
						 ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			httpRequest.setCharacterEncoding(encoding);
			httpResponse.setCharacterEncoding(encoding);
			// CharsetEncodingFilter -> FrontControllerServlet -> forward -> index.jsp
		}

		// 执行过滤链
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}
}
